<?php

namespace App\Utility;

use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\Spl\SplString;

class MiniProgram{
    const API_BASE = 'https://api.weixin.qq.com/';
    protected $app;
    protected $apis = [
        'access_token' => self::API_BASE.'cgi-bin/token',
        'session_key'  => self::API_BASE.'sns/jscode2session',
    ];
    protected $cachePrefix = 'wechat.mini.';
    function __construct(){
        $this->app = Config::getInstance()->getConf('WECHAT_MINI_PROGRAM');
    }

    //基本配置
    private function getConfig(): array{
        return [
            'appid' => $this->app['APPID'],
            'secret' => $this->app['SECRET'],
        ];
    }

    /**
     *  Get session info by code.
     * @param string $code
     * @return mixed
     */
    public function session(string $code){
        $config = $this->getConfig();
        $config = array_merge(['js_code' => $code,'grant_type'=>'authorization_code'],$config);
        $params = ['query' => $config];
        return $this->sendRequest('GET',$this->apis['session_key'],$params);

    }

    /**
     * send a http request
     * @param string $method
     * @param string $url
     * @param array $params
     * @return mixed|void
     */
    private function sendRequest(string $method='GET',string $url='', array $params=[]){
        if(empty($url)){
            return ;
        }
        $request = new Curl();
        $result = $request->request($method,$url, $params);
        $string = new SplString($result);
        return json_decode($string, true);
    }

    //获取token
    private function getToken(){

    }

    //请求token
    private function requestToken(){
        $config = $this->getConfig();
        $config = array_merge(['grant_type'=>'client_credential'],$config);
        $params = ['query' => $config];
        return $this->sendRequest('GET',$this->apis['access_token'],$params);
    }

    //保存token
    private function setToken(){

    }

    //刷新token
    private function refreshToken(){

    }
}
